<template>
  <div>
    <el-form :model="params" ref="ruleForm" label-width="180px" class="item" size="small">
      <el-row class="head">配送业务</el-row>
      <el-row class="body">
        <el-row type='flex'>
          <el-form-item label='基础配送距离' required style="margin-bottom: 0;">
            <el-row type='flex'>
              <el-form-item prop="basedistance" :rules="[{required: true, message: '请输入距离'} ]">
                <el-input-number placeholder="请输入距离" :min='0' :max="99" :precision='0' v-model="params.basedistance" />
                <span style='margin: 0 5px;'>{{comConfig.length}}({{comConfig.lengthUnit}})</span>
              </el-form-item>
              <el-form-item prop='basictime' :rules="[{required: true, message: '基础时间分钟未填'},]">
                <el-input-number placeholder="请输入分钟" :min='0' :max="99" :precision='0' v-model="params.basictime" />
                <span style='margin: 0 5px;'>mm(分钟)</span>
              </el-form-item>
            </el-row>
          </el-form-item>
        </el-row>
        <el-row type='flex'>
          <el-form-item label="代购基础配送费" prop="daigoubasecost" :rules="[{required: true, message: '代购基础配送费未填'}]">
            <el-input-number placeholder="请输入金额" :min='0' :max="99" :precision='2' v-model="params.daigoubasecost" />
            <span style='margin-left: 5px'>{{comConfig.unit}}</span>
          </el-form-item>
        </el-row>
        <el-row type='flex'>
          <el-form-item label="取送件基础配送费" prop="qusongjianbasecost" :rules="[ {required: true, message: '取送件基础配送费未填'} ]">
            <el-input-number placeholder="请输入金额" :min='0' :max="99" :precision='2' v-model="params.qusongjianbasecost" />
            <span style='margin-left: 5px'>{{comConfig.unit}}</span>
          </el-form-item>
        </el-row>
        <el-form-item label="超出部分距离附加费" style="margin-bottom: 0">
          <el-row type="flex">
            <el-row>
              <el-row type="flex" v-for="(item,index) in params.paotuiCostDistanceList" :key="index">
                <el-form-item style="width: 120px;">
                  <el-input type='number' :value='index== 0?0:params.paotuiCostDistanceList[index-1].enddistance' disabled clearable />
                </el-form-item>
                <span style='margin: 0 5px;'>至</span>
                <el-form-item :prop="'paotuiCostDistanceList.' + index + '.enddistance'" :rules="[{required: true, message: '距离未填'}]">
                  <el-input-number :precision='0' v-model="item.enddistance" :min='index==0?1:params.paotuiCostDistanceList[index-1].enddistance+1'
                    :max="index < (params.paotuiCostDistanceList.length-1) ? (params.paotuiCostDistanceList[index+1].enddistance-1) :999" />
                </el-form-item>
                <span style=';margin:0 5px;'>{{comConfig.length}}({{comConfig.lengthUnit}})的部分，每{{comConfig.lengthUnit}}加收</span>
                <el-form-item :prop="'paotuiCostDistanceList.' + index + '.fee'" :rules="[{required: true, message: '金额未填'}]">
                  <el-input-number :min='0' :max="999" :precision='2' v-model="item.fee" />
                </el-form-item>
                <span style='margin: 0 5px;'>{{comConfig.unit}}</span>
                <div v-if="index== (params.paotuiCostDistanceList.length-1)" class="flex-row-ver butnsdel" @click="delDistanceCharge()">
                  <i class="el-icon-remove"></i>
                </div>
              </el-row>
            </el-row>
             <div v-if='params.paotuiCostDistanceList.length< 10' class="butns" >
            <el-button type='primary' style='padding: 6px 4px' size='mini' :disabled='isshow1' icon='el-icon-circle-plus-outline' @click="addDistanceCharge()">
              ({{params.paotuiCostDistanceList.length}}/10)
            </el-button>
          </div>
          </el-row>
        </el-form-item>

        <el-form-item label="重量附加费" style="margin-bottom: 0">
          <el-row type="flex">
            <el-row>
              <el-row type="flex" v-for="(item,index) in params.paotuiCostWeightList" :key="index">
                <el-form-item style="width: 120px;">
                  <el-input type='number' :value='index==0? 0:params.paotuiCostWeightList[index-1].endweight' disabled  clearable />
                </el-form-item>
                <span style='margin: 0 5px;'>至</span>
                <el-form-item :prop="'paotuiCostWeightList.' + index + '.endweight'" :rules="[{required: true, message: '重量未填写'}]">
                  <el-input-number :min='index==0?1:params.paotuiCostWeightList[index-1].endweight+1' :precision='0' v-model="item.endweight"
                    :max="index<(params.paotuiCostWeightList.length-1)?(params.paotuiCostWeightList[index+1].endweight-1):999" />
                </el-form-item>
                <span style='margin: 0 5px;'>{{comConfig.weight}}({{comConfig.weightUnit}})的部分，每{{comConfig.weightUnit}}加收</span>
                <el-form-item :prop="'paotuiCostWeightList.' + index + '.fee'" :rules="[{required: true, message: '金额未填写'}]">
                  <el-input-number placeholder="请输入金额" :min='0' :max="999" :precision='2' v-model="item.fee" />
                </el-form-item>
                <span style='margin: 0 5px;'>{{comConfig.unit}}</span>
                <div v-if="index== (params.paotuiCostWeightList.length-1)" class="flex-row-ver butnsdel" @click="delWeightSurcharge()">
                  <i class="el-icon-remove"></i>
                </div>
              </el-row>
            </el-row>
            <div v-if='params.paotuiCostWeightList.length< 10' class="butns" >
              <el-button type='primary' style='padding: 6px 4px' size='mini' :disabled='isshow2' icon='el-icon-circle-plus-outline' @click="addWeightSurcharge()">
                ({{params.paotuiCostWeightList.length}}/10)
              </el-button>
            </div>
          </el-row>
        </el-form-item>
        <el-form-item label="特需时段附加费" style="margin-bottom: 0">
          <el-row type="flex">
            <el-row>
              <el-row type="flex" v-for="(item,index) in params.paotuiCostTimeList" :key="index">
                <el-form-item :prop="'paotuiCostTimeList.' + index + '.startDate'" :rules="[{required: true, message: '时间点未填写'}]">
                  <el-time-select style='width: 150px' placeholder="起始时间" v-model="item.startDate" :clearable='false'
                    :picker-options="{ start: '00:00',step: '00:30',end: '24:00',
                    minTime:index==0?'':toMillisecond(params.paotuiCostTimeList[index-1].endDate),
                    maxTime:item.endDate}" />
                </el-form-item>
                <span style='margin: 0 5px;'>至</span>
                <el-form-item :prop="'paotuiCostTimeList.' + index + '.endDate'" :rules="[{required: true, message: '时间点未填写'}]">
                  <el-time-select style='width: 150px' placeholder="结束时间" v-model="item.endDate" :clearable='false'
                    :picker-options="{ start: '00:00',step: '00:30',end: '24:00',minTime: item.startDate,
                      maxTime:index<(params.paotuiCostTimeList.length-1)?(params.paotuiCostTimeList[index+1].startDate):'' }">
                  </el-time-select>
                </el-form-item>
                <span style='margin: 0 5px;'>时间内，每单加收</span>
                <el-form-item :prop="'paotuiCostTimeList.' + index + '.fee'" :rules="[{required: true, message: '金额未填写'}]">
                  <el-input-number placeholder="请输入金额" :min='0' :max="999" :precision='2' v-model="item.fee" />
                </el-form-item>
                <span style='margin: 0 5px;'>{{comConfig.unit}}</span>
                <div v-if="index== (params.paotuiCostTimeList.length-1)" class="flex-row-ver butnsdel" @click="delTimeSurcharge()">
                  <i class="el-icon-remove"></i>
                </div>
              </el-row>
            </el-row>
             <div v-if='params.paotuiCostTimeList.length< 10' class="butns" >
              <el-button type='primary' style='padding: 6px 5px' size='mini' :disabled='isshow3' icon='el-icon-circle-plus-outline' @click="addTimeSurcharge()">
                ({{params.paotuiCostTimeList.length}}/10)
              </el-button>
            </div>
          </el-row>
        </el-form-item>

        <el-form-item label='加时规则' required>
          <el-row type='flex'>
            <span style='margin: 0 5px;'>每</span>
            <el-form-item prop='overtimedistance' :rules="[{required: true, message: '加时规则距离未填'}]">
              <el-input-number :min='0' :max="999" :precision='0' v-model="params.overtimedistance" />
            </el-form-item>
            <span style='margin: 0 5px;'>{{comConfig.length}}({{comConfig.lengthUnit}})</span>
            <el-form-item style='width: 200px' prop='overtimetime' :rules="[{required: true, message: '加时规则分钟未填'}]">
              <el-input-number  :min='0' :max="999" :precision='0' v-model="params.overtimetime" />
              <span style='margin: 0 5px;'>mm(分钟)</span>
            </el-form-item>
          </el-row>
        </el-form-item>
      </el-row>
      <el-form-item>
        <el-button type="primary" :loading="issubmitLoading" @click="submitForm('ruleForm')">保存</el-button>
      </el-form-item>
    </el-form>
    <div v-if="infoLoading" class="info-loading-addShop"></div>
  </div>
</template>
<script>
  import { kmToOtherUnit, otherUnitToKm, kgToOtherUnit, otherUnitToKg } from '@/utils/unitChange.js'
  export default {
    data() {
      return {
        infoLoading: false, // 页面加载数据等待
        issubmitLoading: false, // 提交等待
        params: {
          agentid: this.$route.query.aid, // 区域id
          basedistance: undefined, // 基础配送费
          basictime: undefined, // 基础时间分钟
          daigoubasecost: undefined, // 代购基础配送费
          qusongjianbasecost: undefined, // 取送件基础配送费
          /*commissionRate: undefined, // 永久比例*/
          paotuiCostDistanceList: [], // 距离附加费
          paotuiCostWeightList: [], // 重量附加费
          paotuiCostTimeList: [], // 特需时段附加费
          overtimetime: undefined, // 加时规则分钟
          overtimedistance: undefined // 加时规则距离
        },
        isshow1:false,
        isshow2:false,
        isshow3:false,
      }
    },
    watch: {
      'params.paotuiCostDistanceList': {
        handler(newValue, oldValue) {
          this.isshow1 = this.isShowEbutton1(newValue)
        },
        deep: true
      },
      'params.paotuiCostWeightList': {
        handler(newValue, oldValue) {
          this.isshow2 = this.isShowEbutton2(newValue)
        },
        deep: true
      },
      'params.paotuiCostTimeList': {
        handler(newValue, oldValue) {
          this.isshow3 = this.isShowEbutton3(newValue)
        },
        deep: true
      }
    },
    methods: {
      toMillisecond(str){
        if(str){
          var arr = str.split(':');
          var t= Number(arr[0]*60)+Number(arr[1])-1;
          let checkMint = (n) =>{
            if(n < 10) return '0' +n
            else return n
          }
          return checkMint(Math.floor(t/60))+':'+checkMint( Math.ceil(t%60))
        }else{
          return ''
        }
      },
      isShowEbutton1(arr){
        let isShow = false
        if (arr.length) {
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].enddistance === '' || arr[i].fee === '') {
              isShow = true
            }
          }
        }
        return isShow
      },
      isShowEbutton2(arr){
        let isShow = false
        if (arr.length) {
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].endweight === '' || arr[i].fee === '') {
              isShow = true
            }
          }
        }
        return isShow
      },
      isShowEbutton3(arr){
        let isShow = false
        if (arr.length) {
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].startDate === '' || arr[i].endDate === '' || arr[i].fee === '') {
              isShow = true
            }
          }
        }
        return isShow
      },
      addDistanceCharge() {
        this.params.paotuiCostDistanceList.push({ enddistance: '', fee: '',costid:'' })
      },
      addWeightSurcharge() {
        this.params.paotuiCostWeightList.push({ endweight: '', fee: '',costid:'' })
      },
      addTimeSurcharge() {
        this.params.paotuiCostTimeList.push({ startDate:'', endDate:'', fee: '', costid:'' })
      },
      delDistanceCharge() {
        this.params.paotuiCostDistanceList.pop()
      },
      delWeightSurcharge() {
        this.params.paotuiCostWeightList.pop()
      },
      delTimeSurcharge() {
        this.params.paotuiCostTimeList.pop()
      },
      submitForm(formName) { //提交数据
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const params = JSON.parse(JSON.stringify(this.params))
            params.overtimedistance = otherUnitToKm(params.overtimedistance)
            params.basedistance = otherUnitToKm(params.basedistance)
            params.paotuiCostDistanceList.forEach((item,index)=>{
              params.paotuiCostDistanceList[index].enddistance = otherUnitToKm(params.paotuiCostDistanceList[index].enddistance)
              if (index == 0) {
                params.paotuiCostDistanceList[0].startdistance = 0
              } else {
                params.paotuiCostDistanceList[index].startdistance = params.paotuiCostDistanceList[index-1].enddistance
              }
            })
            params.paotuiCostWeightList.forEach((item,index)=>{
              params.paotuiCostWeightList[index].endweight = otherUnitToKg(params.paotuiCostWeightList[index].endweight)
              if (index == 0) {
                params.paotuiCostWeightList[0].startweight = 0
              } else {
                params.paotuiCostWeightList[index].startweight = params.paotuiCostWeightList[index-1].endweight
              }
            })
            this.issubmitLoading = true
            if (this.$route.query.id) {
              params.id = this.$route.query.id
              this.$http.post('/server/paotui/cost/update', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.$message({type: 'success', message: '修改成功!'})
                  this.$router.push({path: '/main/fwbeset/list'})
                }
              }).finally(() => { this.issubmitLoading = false })
            } else {
              this.$http.post('/server/paotui/cost/save', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.$message({type: 'success', message: '添加成功!'})
                  this.$router.push({path: '/main/fwbeset/list'})
                }
              }).finally(() => { this.issubmitLoading = false })
            }
          } else {
            this.$alert('有不合法的输入，请检查页面修改再提交', '提示！')
            return false
          }
        });
      },
      getTableListInfo() { //获取当前页面数据
        const params = {id: this.$route.query.id, agentid: this.$route.query.aid}
        this.infoLoading = true
        this.$http.get('/server/paotui/cost/info?' + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            const row = res.data.data
            this.params.basedistance = row.basedistance ? kmToOtherUnit(row.basedistance) : undefined
            this.params.daigoubasecost = row.daigoubasecost
            this.params.qusongjianbasecost = row.qusongjianbasecost
            this.params.commissionRate = row.commissionRate

            this.params.paotuiCostTimeList = row.paotuiCostTimeList
            this.params.basicsDis = row.basicsDis
            this.params.basictime = row.basictime
            this.params.overtimetime = row.overtimetime
            this.params.overtimedistance = row.overtimedistance ? kmToOtherUnit(row.overtimedistance) : undefined

            const paotuiCostDistanceList = row.paotuiCostDistanceList
            const paotuiCostWeightList = row.paotuiCostWeightList

            paotuiCostDistanceList.forEach((item,index)=>{
              delete item.startdistance
              item.enddistance = item.enddistance ? kmToOtherUnit(item.enddistance) : undefined
            })
            paotuiCostWeightList.forEach((item,index)=>{
              delete item.startweight
              item.endweight = item.endweight ? kgToOtherUnit(item.endweight) : undefined
            })
            this.params.paotuiCostDistanceList = paotuiCostDistanceList
            this.params.paotuiCostWeightList = paotuiCostWeightList
          }
        }).finally(() => { this.infoLoading = false })
      }
    },
    mounted() {
      if (this.$route.query.aid) {
        if (this.$route.query.id) {
          this.getTableListInfo()
        }
      } else {
        this.$router.push('/main/fwbeset/list')
        this.$message.error('当前页面参数丢失，已返回列表页')
      }
    }
  }
</script>
<style scoped>
  .item {
    max-width: 1200px;
    margin: 0 auto;
  }

  .item .head {
    height: 40px;
    line-height: 32px;
    padding: 0 15px;
    border-radius: 4px;
    justify-content: space-between;
    font-weight: bold;
    background: #eff0f5;
  }

  .item .body {
    padding-top: 20px;
    margin-bottom: 30px;
    border: 1px solid #dad4d4;
    border-top: none;
  }

  .item .butns {
    cursor: pointer;
    text-align: center;
    margin-left: 20px;
    padding: 0 5px;
    height: 40px;
    line-height: 32px
  }

  .item .butns i {
    font-size: 25px;
    color: #409eff;
  }

  .item .butnsdel {
    cursor: pointer;
    text-align: center;
    margin-left: 20px;
    padding: 0 5px;
    height: 32px;
    line-height: 32px
  }

  .item .butnsdel i {
    font-size: 25px;
    color: #f56c6c;
  }
</style>
